<!--
 @description 经销商档案新建-合作伙伴信息
 @fileName Partner.vue
 @author zengqiongying
 @created 2023/04/30 18:07:12
-->
<template>
  <div class="has-foot-pb">
    <Card v-for="(item, i) in list" :key="`${i}-${item.code}`">
      <template #title>
        <div class="card-header">
          <span class="name"><span class="icon"></span>合伙人{{ i + 1 }}</span>
          <span class="btn-del" @click="onDelete(i)"></span>
        </div>
      </template>
      <PartnerItem v-model:modelValue="list[i]" />
    </Card>
    <Card>
      <div class="btn-add-larg" @click="onCreat">
        <qmp-icon name="plus" />
        添加合伙人
      </div>
    </Card>
    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSave()">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import Card from '@/components/Card/index.vue'
  import PartnerItem from '../components/Partner/Item.vue'
  import { detail } from '@/apis/dealerMarketing/NewArchive'
  import { savePartner } from '@/apis/ctmCustomerChange/index'
  import { validIDCard } from '@/utils/validate'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  const none: any[] = [null, undefined, '']
  interface datasModle {
    [key: string]: any
  }
  export default {
    name: 'DealerNewArchivePartner',
    components: { Card, PartnerItem },
    setup() {
      const { proxy }: any = getCurrentInstance()
      const $router = useRouter()
      const $route = useRoute()
      const defaultData = {
        name: '',
        tel: '',
        credentialNo: ''
      }
      const datas = reactive<datasModle>({
        id: $route.query.id || '',
        list: []
      })
      datas.keyboard = {
        show: false
      }
      datas.keyboard = GetKeyboardMixin()

      const onCreat = () => {
        const obj: any = { ...defaultData, ...{ code: 'TS' + new Date().getTime() } }
        datas.list.push(obj)
      }
      const onSave = () => {
        let flag = false
        const list = datas.list.map((v: any) => {
          const itemData = { ...v }
          for (const [k, val] of Object.entries(v)) {
            if (none.includes(val)) {
              flag = true
            }
          }

          if (v.code && v.code.indexOf('TS') === 0) {
            delete itemData.code
          }
          itemData.changeCode = datas.changeCode

          return itemData
        })
        if (flag) {
          proxy.$toast('请检查必填项是否填写完整')
          return
        }
        const regPhone = /^([1]\d{10}|([\(（]?0[0-9]{2,3}[）\)]?[-]?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$/
        let idNoPass: any[] = []
        let telNoPass: any[] = []
        list.forEach((v: any, i: number) => {
          if (v.credentialNo && !validIDCard(v.credentialNo)) {
            idNoPass.push(i + 1)
          }
          if (!regPhone.test(v.tel)) {
            telNoPass.push(i + 1)
          }
        })
        if (idNoPass.length > 0 || telNoPass.length > 0) {
          let errorMsg = ''
          if (idNoPass.length > 0) {
            errorMsg = errorMsg + `身份证号码无效：合伙人${idNoPass.join(',')}`
          }
          if (telNoPass.length > 0) {
            if (errorMsg) {
              errorMsg += '\n'
            }
            errorMsg = errorMsg + `联系电话无效：合伙人${telNoPass.join(',')}`
          }
          proxy.$dialog.alert({
            title: '以下数据不合规范',
            message: errorMsg,
            allowHtml: true,
            messageAlign: 'left'
          })
          return
        }

        savePartner(list, datas.changeCode).then((res: any) => {
          if (res.success === 1) {
            proxy.$toast('保存成功')
            proxy.$SimpleEvents.emit('refreshCustomerNewArchiveEditInfo', datas.id)
            nextTick(() => {
              $router.goBack()
            })
          }
        })
      }

      const onDelete = (i: number) => {
        datas.list.splice(i, 1)
      }

      const getList = () => {
        const id = `${datas.id}`
        detail(id).then((res: any) => {
          if (res.data) {
            datas.changeCode = res.data?.code || ''
            datas.list = res.data?.partnerDTOS || []
          }
        })
      }

      getList()

      return {
        ...toRefs(datas),
        onSave,
        onCreat,
        onDelete
      }
    }
  }
</script>
<style lang="less" scoped>
  @import url('../styles/common.less');
</style>
